<template>
  <span v-if="this.infoshow">亲，您还没有选购任何商品呢！</span>
    <!-- 卡片视图区域 -->
    <el-card class="el-card" v-if="!this.infoshow">
      <!-- 购物车商品展示 -->
      <el-table :data="showCarts" :row-class-name="rowStyle" class="el-table">
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column label="商品名称" prop="animal.good_specific"></el-table-column>
        <el-table-column label="商品图片" prop="animal.url" show-overflow-tooltip>
          <template v-slot="scope"> <img :src="showCarts[scope.$index].animal.url" style="width: 50px;">
          </template>
        </el-table-column>
        <el-table-column label="商品价格" prop="animal.price"></el-table-column>
        <el-table-column label="商品数量" prop="number"></el-table-column>
        <el-table-column label="操作" class="el-table-column">
          <template v-slot="scope">
            <!-- 删除按钮 -->
            <el-button type="danger" @click="deletegood(scope.$index, showCarts[scope.$index].cart_id)">删除</el-button>
            <!-- 选择按钮 -->
            <el-button :style="{background: this.selected.indexOf(showCarts[scope.$index].cart_id)<0 ? '#909399'  : '#67C23A' }" 
            @click="selectgood($event, showCarts[scope.$index].animal.price, 
            showCarts[scope.$index].number, showCarts[scope.$index].cart_id)" type="info">
            {{this.selected.indexOf(showCarts[scope.$index].cart_id)<0 ? "未选择" : "已选择"}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
      v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
      :page-sizes="[5,10,15,20]" :small="small" :disabled="disabled" :background="background"
      layout="total, sizes, prev, pager, next, jumper" :total=CartsLength
      @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      <el-label>你已选择{{ this.totalnum }}件商品，总金额为{{ this.totalmoney }}元</el-label>
    </el-card>
    <el-button @click="dialogFormVisibleAppear" v-if="!this.infoshow">提交订单</el-button>

  <el-dialog v-model="dialogFormVisible" title="详细信息">
    <el-form :model="form">
      <el-form-item label="地址信息" :label-width="formLabelWidth">
        <el-select
            placeholder="请选择地址"
            class="selectAddress"
            v-model="addressinfo"
            clearable
            filterable
            @blur.capture="selectBlur">
          <el-option v-for="address in addresses"
           :key="address.address_id"
           :value="address.address"
           :label="address.address">
          </el-option>
        </el-select>
        <span v-show="form.addressError" class="error_tip">地址信息不能为空</span>
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input v-model="form.remarks" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFormVisibleClose()">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  </template>

  
<script>
  import { onMounted, ref, reactive } from 'vue'
  import axios from 'axios'
  import { ElMessage, ElMessageBox } from 'element-plus'


  export default {
    data(){
      return{
        user: {},
        //购物车列表
        Carts: [],
        //用于展示的购物车列表
        showCarts:[] ,
        //被选中行的编号
        selected: [],
        //购物车总列表的长度
        CartsLength: 0,
        //该用户的地址列表
        addresses: [],
        infoshow: false,
        queryInfo: {
          //当前页数
          pagenum: 1,
          //当前每页显示多少条数据
          pagesize: 5
        },
        //总金额
        totalmoney: 0,
        //选择总件数
        totalnum: 0,
        //当前用户id
        user_id: 0,
        //表单数据绑定
        form: reactive({
          address: '',
          remarks: '',
          addressError: false,
          addressErrorText: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: '',
        }),
        //
        dialogFormVisible: ref(false),
        addressinfo: ref('')
      }
    },
    created(){
      this.getCarts()
    },
    mounted() {
      this.user = JSON.parse(localStorage.getItem("user"))
    },
    methods:{
      //获取购物车
      getCarts(){
        this.user_id = JSON.parse(localStorage.getItem("user")).id //获取user_id
        onMounted(async() => {
          axios.get("http://127.0.0.1:8080/cart/" + this.user_id)
          .then(response => {
              // 处理成功情况
              this.Carts = response.data.data
              this.showCarts = this.Carts
              this.CartsLength = this.Carts.length
              this.changeshowCarts()
              if(this.CartsLength == 0){
                this.infoshow = true
              }
          })
          .catch(error => {
            //处理错误
            console.log(error)
          })
        })
      },
      //删除商品
      deletegood(index,id){
        //提示框
        ElMessageBox.confirm(
          '真的要把我移出购物车嘛/(ㄒoㄒ)/~~',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {        
          //删除购物车商品
          console.log(id)
          axios.delete("http://127.0.0.1:8080/cart/delete/" + id)
          //判断要删除的商品是否在已被选择
          let temp=this.selected.indexOf(id)
          if(temp>=0)
            this.selected.splice(temp,1)
          //找到id对应下标
          for(let i=0;i<this.CartsLength;i++){
            if(this.Carts[i].cart_id == id){
              this.Carts.splice(i,1)
              break;
            }
          }
          console.log(this.Carts)
          this.CartsLength--
          this.changeshowCarts()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }).catch((error) => {
          //取消操作
          console.log(error)
          ElMessage({
            type: 'info',
            message: '操作已取消',
          })
        })
      },
      //选择商品
      selectgood(event, price, num, id){
        let flag = false,
            index = this.selected.indexOf(id)

        //判断该商品是否被选中
        if(index < 0){
          this.selected.push(id)  //之前未被选中，代表现在被选中
          flag = true
        }
        if(flag){
          this.totalnum += num
          this.totalmoney += price*num
        }else{
          this.totalnum -= num
          this.totalmoney -= price*num
          this.selected.splice(index,1)
        }
      },
      //修改展示列表
      changeshowCarts(){
        this.showCarts = []
        let i = (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize       
        do{
          this.showCarts.push(this.Carts[i])
          i++
        }while(i<this.queryInfo.pagesize * this.queryInfo.pagenum && i<this.CartsLength)
      },
      //监听 pagesize 改变事件
      handleSizeChange(newSize){
        this.queryInfo.pagesize = newSize
        this.showCarts = undefined
        this.changeshowCarts()
      },
      //监听页码值改变事件
      handleCurrentChange(newPage){
        this.queryInfo.pagenum = newPage
        this.showCarts = undefined
        this.changeshowCarts()
      },
      dialogFormVisibleAppear(){
        if(this.selected.length == 0){
          ElMessageBox.alert('您尚未选择商品哦','提示',{
            confirmButtonText: '返回购物车继续选择'
          })
        }else{
          axios.get("http://127.0.0.1:8080/address/" + this.user_id)
          .then(response => {
            this.addresses = response.data.data
            console.log(this.addresses)
          }).catch(error => {
            ElMessage({
            type: 'error',
            message: '哦哦，系统出错，请稍后再试',
          })
          })
      
          this.dialogFormVisible = true
        }
      },
      //提交
      dialogFormVisibleClose(){
        console.log(this.addressinfo)
        this.form.addressError = false
        if(this.addressinfo.length > 0){
          this.dialogFormVisible = false
          //提示框
          ElMessageBox.confirm(
            '是否确认提交',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(() => {     
            //删除被选择的商品
            console.log(this.addressinfo)
            for(let i=0;i<this.selected.length;i++){
              //生成对应订单
              axios.post("http://127.0.0.1:8080/cart/submit?cart_id="+ this.selected[i] +"&user_id=" + this.user_id +
              "&remark=" + this.form.remarks + "&address=" + this.addressinfo)
              .then(response => console.log("订单生成成功！"))
              .catch(error => console.log(error))

              axios.delete("http://127.0.0.1:8080/cart/delete/" + this.selected[i])
              .then(response => console.log("成功将商品从购物车移出！"))
              .catch(error => console.log(error))

            }
            location.reload()
          }).catch((error) => {
            console.log(error)
            ElMessage('操作已取消')
          })  
        }else{
          this.form.addressError = true
          ElMessageBox.alert(
            '地址信息不能为空',
            '提示！',
            {
              confirmButtonText: 'OK'
            }
          )
        }
        
      },
      addressCheck(){
        if(this.addressinfo.length > 0){
          this.form.addressError = false
        }else{
          this.form.addressError = true
        }
      },
      selectBlur(e) {
        this.addressCheck()
        console.log(this.addressinfo)
        if(e.target.value.length>0){
          for(let i=0;i<this.addresses.length;i++){
            if(e.target.value==this.addresses[i].address){
              return
            }
          }
          this.$axios
              .post(`${this.$target}/address/save?id=`+this.user.id+`&&address=`+e.target.value, {
                headers: {
                  'Content-Type': 'application/json;charset=UTF-8'
                }
              })
              .then(res => {
                axios.get("http://127.0.0.1:8080/address/" + this.user_id)
                    .then(response => {
                      this.addresses = response.data.data
                      this.$forceUpdate();
                      this.addressinfo = e.target.value
                    }).catch(error => {
                  ElMessage({
                    type: 'error',
                    message: '哦哦，系统出错，请稍后再试',
                  })
                })
              })
        }

      }
      }
    }
  
</script>
  
<style>
  .el-card{
    box-shadow: 0 1px 1px rgba(0,0,0,0.15) !important;
  }
  
  .el-table{
    margin-top: 15px;
  }

  .el-table .el-table-column .el-button .selectcolor{
    background: #67C23A;
  }

  .el-table .el-table-column .el-button .defaultcolor{
    background: #909399;
  }
  
  .error_tip{
    color: red
  }

  .creatAddressBtn{
    margin-left: auto;
    margin-right: 0;
  }

  .selectAddress{
    width: auto;
  }

  .selectAddress .el-input{
    width: auto;
  }
</style>